#include <QApplication>
#include <QQmlApplicationEngine>
#include <QLibrary>
#include <QDebug>
#include <QVector>
#include <QQuickItem>
#include <memory>
#include "PluginEngine.h"


#ifdef Q_OS_WIN
#define ENGINELIBNAME "EAEngine.dll"
#else
#define ENGINELIBNAME "libEAEngine.so"
#endif

using namespace EAEngine;
typedef QObject* (*Function)();
void PluginInit();

std::unique_ptr<PluginEngine> instance_ptr;

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

//    QList<QObject*> listObj = engine.rootObjects();
//    QList<QObject*> listItem = listObj[0]->findChildren<QObject *>("buttonCplus");
//    QObject *button = rootItem->findChild<QObject *>("buttonCplus");
//    QObject *button1 = engine.rootObjects()[0]->findChild<QObject *>("buttonCplus");

    PluginInit();

    return app.exec();
}

void PluginInit()
{
    qDebug()<<"start loading plugin...";
    QLibrary qlib(ENGINELIBNAME);
    if(qlib.load())
    {
        qDebug()<<"DLL is loaded success!";
        Function functionPointer = (Function)qlib.resolve("GetInstance");
        if(functionPointer)
        {
            QPointer<PluginEngine>instance = qobject_cast<PluginEngine *>(functionPointer());
            instance_ptr=std::unique_ptr<PluginEngine>(instance.data());
            if(instance)
            {
                QVector<EAEngine::IPluginObject*>* plugins = instance->GetPlugins();
                for(QVector<EAEngine::IPluginObject*>::iterator itr=plugins->begin();
                    itr!=plugins->end();++itr)
                {
                    EAEngine::IPluginObject* plugin = *itr;
                    qDebug()<<plugin->GetPluginText();
                }
            }
            qDebug()<<"function is resolved success!";
        }else
        {
            qDebug()<<"function is resolved failed!";
        }
        qlib.unload();
    }
    else
    {
        qDebug()<<"DLL is not loaded!";
    }
}
